# @Time : 2020/12/4 10:40
# @Author : Fioman 
# @Phone : 13149920693
"""
日志文件,用来保存日志使用
"""
import datetime
import logging
import os

BASEDIR = os.path.dirname(os.path.abspath(__file__))


def log_check():
    debugDir = os.path.join(BASEDIR, "debug")
    if not os.path.exists(debugDir):
        os.mkdir(debugDir)
    nowTime = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")

    try:
        for root, _, filenames in os.walk(debugDir):
            for filename in filenames:
                day = filename[8:10]
                month = filename[5:7]
                nowDay = nowTime[8:10]
                nowMonth = nowTime[5:7]
                if nowDay == day and nowMonth != month:  # 如果天数相同,但是月数不同,就删除上个月同一天的日志信息
                    os.remove(os.path.join(debugDir, filename))
    except Exception as e:
        print(str(e))

    finally:
        return nowTime, debugDir


def log_init(name):
    nowTime, debugDir = log_check()  # 获取当前时间
    logger = logging.getLogger(name)
    logger.setLevel(level=logging.DEBUG)
    handler = logging.FileHandler(os.path.join(debugDir, nowTime) + "debug.txt", encoding='utf-8')
    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s - %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger


